package com.devplatform.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.devplatform.pojo.article.Article;
import com.devplatform.pojo.article.ArticleBan;
import com.devplatform.pojo.dto.ArticleBanDto;
import com.devplatform.pojo.dto.ArticleUnBanDto;
import com.devplatform.pojo.dto.BanUserDto;
import com.devplatform.pojo.user.User;
import com.devplatform.pojo.user.UserBan;
import com.devplatform.pojo.vo.DataVo;
import com.devplatform.service.article.ArticleService;
import com.devplatform.service.impl.UserService;
import com.devplatform.service.impl.article.ArticleBanServiceImpl;
import com.devplatform.service.user.UserBanService;
import com.devplatform.util.MessageUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//后台控制层
@RestController
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@RequestMapping("/api/system")
public class SystemRootController {

    public final MessageUtil messageUtil;

    public final UserService userService;

    public final UserBanService userBanService;
    public final ArticleService articleService;
    public final ArticleBanServiceImpl articleBanService;

    //查看所有用户
    @GetMapping("/getList")
    public DataVo getList(
            @RequestParam(defaultValue = "1", name = "currentPage") Integer pageNum,//页码
            @RequestParam(defaultValue = "10", name = "pageSize") Integer pageSize,//展示条数
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String email

    ) {

        Page<User> page = new Page<>(pageNum, pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0);
        if (StringUtils.hasText(username)) {
            queryWrapper.like("username", username);
        }
        if (StringUtils.hasText(email)) {
            queryWrapper.like("email", email);
        }
        IPage<User> resultPage = userService.page(page, queryWrapper);
        return DataVo.ok(resultPage);
    }

    //更新单个用户
    @PutMapping("/updateStatus")
    public DataVo updateStatus(@RequestBody Map<String, Object> params) {
        try {
            Long userId = Long.valueOf(params.get("userId").toString());
            Integer userStatusId = Integer.valueOf(params.get("userStatusId").toString());

            User user = userService.getById(userId);
            if (user != null) {
                // 保存原始状态用于消息提示
                Integer oldStatus = user.getUserStatusId();
                user.setUserStatusId(userStatusId);
                boolean updateSuccess = userService.updateById(user);

                if (updateSuccess) {
                    // 发送状态变更通知
                    String action = userStatusId == 1 ? "被封禁" : "被解封";
                    String content = String.format("您的账号状态已%s，如有疑问请联系客服", action);
                    messageUtil.sendSecurityMessage(userId, content);

                    return DataVo.ok("状态更新成功");
                } else {
                    return DataVo.error("状态更新失败");
                }
            } else {
                return DataVo.error("用户不存在");
            }
        } catch (Exception e) {
            return DataVo.error("状态更新失败");
        }
    }

    //查询被ban的用户历史信息
    @GetMapping("/banList")
    public DataVo banList(
            @RequestParam(defaultValue = "1", name = "currentPage") Integer pageNum,
            @RequestParam(defaultValue = "10", name = "pageSize") Integer pageSize,
            @RequestParam(required = false) String userId,
            @RequestParam(required = false) String userBanType
    ) {
        Page<UserBan> page = new Page<>(pageNum, pageSize);
        QueryWrapper<UserBan> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(userId)) {
            queryWrapper.eq("user_id", userId);
        }
        if (StringUtils.hasText(userBanType)) {
            queryWrapper.eq("user_ban_type", userBanType);
        }
        queryWrapper.orderByDesc("ban_time");

        IPage<UserBan> resultPage = userBanService.page(page, queryWrapper);
        return DataVo.ok(resultPage);
    }

    //封禁多个用户
    @PutMapping("/banUsers")
    public DataVo banUsers(@RequestBody BanUserDto request) {
        List<Long> userIds = request.getUserIds();
        String userBanType = request.getUserBanType();
        String userReason = request.getUserReason();
        if (userIds == null || userIds.isEmpty()) {
            return DataVo.error("用户ID列表不能为空");
        }
        if (userBanType == null || userBanType.isEmpty()) {
            return DataVo.error("封禁类型不能为空");
        }
        if (userReason == null || userReason.isEmpty()) {
            return DataVo.error("封禁原因不能为空");
        }
        List<User> users = new ArrayList<>();
        for (Long userId : userIds) {
            User user = new User();
            user.setUserId(userId);
            user.setUserStatusId(1);
            users.add(user);
        }
        if (!userService.updateBatchById(users)) {
            return DataVo.error("状态更新失败");
        }
        LocalDateTime currentTime = LocalDateTime.now();
        List<UserBan> userBans = userIds.stream().map(userId -> {
            UserBan ban = new UserBan();
            ban.setUserId(userId);
            ban.setUserBanType(userBanType);
            ban.setUserReason(userReason);
            ban.setBanTime(currentTime);
            return ban;
        }).collect(Collectors.toList());

        boolean saveSuccess = userBanService.saveBatch(userBans);
        if (!saveSuccess) {
            return DataVo.error("封禁记录保存失败");
        }
        String action = "被封禁";
        String contentTemplate = String.format("您的账号因【%s】被%s，原因：%s", userBanType, action, userReason);
        for (Long userId : userIds) {
            messageUtil.sendSecurityMessage(userId, contentTemplate);
        }

        return DataVo.ok("封禁成功，已发送通知");
    }

    // 封禁文章
    @PutMapping("/articleBan/banArticles")
    public DataVo banArticles(@Validated @RequestBody ArticleBanDto banDTO) {
        List<Long> articleIds = banDTO.getArticleIdList();
        String banType = banDTO.getArticleBanType();
        String banReason = banDTO.getArticleBanReason();
        List<Long> userIds = banDTO.getUserIds();
        if (articleIds == null || articleIds.isEmpty()) {
            return DataVo.error("文章ID列表不能为空");
        }
        if (banType == null || banType.isEmpty()) {
            return DataVo.error("封禁类型不能为空");
        }
        if (banReason == null || banReason.isEmpty()) {
            return DataVo.error("封禁原因不能为空");
        }
        if (userIds == null || userIds.isEmpty()) {
            return DataVo.error("用户ID列表不能为空");
        }

        try {
            List<Article> articles = articleIds.stream()
                    .map(articleId -> {
                        Article article = new Article();
                        article.setArticleId(articleId);
                        article.setStatusId(2);
                        return article;
                    })
                    .collect(Collectors.toList());

            if (!articleService.updateBatchById(articles)) {
                return DataVo.error("文章状态更新失败");
            }
            LocalDateTime currentTime = LocalDateTime.now();
            List<ArticleBan> articleBans = articleIds.stream()
                    .map(articleId -> {
                        ArticleBan ban = new ArticleBan();
                        ban.setArticleId(articleId);
                        ban.setArticleBanType(banType);
                        ban.setArticleBanReason(banReason);
                        ban.setBanTime(currentTime);
                        return ban;
                    })
                    .collect(Collectors.toList());

            if (!articleBanService.saveBatch(articleBans)) {
                return DataVo.error("封禁记录保存失败");
            }
            String contentTemplate = String.format("您的文章因【%s】被封禁，原因：%s", banType, banReason);
            userIds.stream()
                    .distinct() // 去除重复用户ID
                    .forEach(userId -> messageUtil.sendSecurityMessage(userId, contentTemplate));

            return DataVo.ok("封禁成功，已发送通知");

        } catch (Exception e) {
            return DataVo.error(e.getMessage() != null ? e.getMessage() : "封禁失败");
        }
    }

    // 修改查询被封禁的文章接口
    @GetMapping("/articleBan/banArticleList")
    public DataVo articleBanList(
            @RequestParam(defaultValue = "1", name = "currentPage") Integer pageNum,
            @RequestParam(defaultValue = "10", name = "pageSize") Integer pageSize,
            @RequestParam(required = false) Long articleId,
            @RequestParam(required = false, name = "articleBanReason") String banReason,
            @RequestParam(required = false) Integer isProcessed,
            @RequestParam(required = false, name = "articleBanType") String banType
    ) {
        Page<ArticleBan> page = new Page<>(pageNum, pageSize);
        QueryWrapper<ArticleBan> queryWrapper = new QueryWrapper<>();
        if (articleId != null) {
            queryWrapper.eq("article_id", articleId);
        }
        if (StringUtils.hasText(banReason)) { // 使用统一后的参数名
            queryWrapper.like("article_ban_reason", banReason);
        }
        if (isProcessed != null) {
            queryWrapper.eq("is_processed", isProcessed);
        }
        if (StringUtils.hasText(banType)) { // 添加封禁类型筛选
            queryWrapper.eq("article_ban_type", banType);
        }
        queryWrapper.orderByDesc("ban_time");
        IPage<ArticleBan> resultPage = articleBanService.page(page, queryWrapper);
        return DataVo.ok(resultPage);
    }

    // 修改文章解封接口
    @PutMapping("/articleBan/unbanArticles")
    public DataVo unbanArticles(@Validated @RequestBody ArticleUnBanDto unbanDTO) {
        List<Long> articleIds = unbanDTO.getArticleIds();
        String unbanReason = unbanDTO.getUnbanReason();
        List<Long> userIds = unbanDTO.getUserIds();
        if (articleIds == null || articleIds.isEmpty()) {
            return DataVo.error("文章ID列表不能为空");
        }
        if (userIds == null || userIds.isEmpty()) {
            return DataVo.error("用户ID列表不能为空");
        }
        if (unbanReason == null || unbanReason.isEmpty()) {
            return DataVo.error("解封原因不能为空");
        }

        try {
            List<Article> articlesList = articleIds.stream()
                    .map(articleId -> {
                        Article article = new Article();
                        article.setArticleId(articleId);
                        article.setStatusId(1);
                        return article;
                    })
                    .collect(Collectors.toList());

            if (!articleService.updateBatchById(articlesList)) {
                return DataVo.error("文章状态更新失败");
            }
            LocalDateTime now = LocalDateTime.now();
            articleIds.forEach(articleId -> {
                ArticleBan ban = new ArticleBan();
                ban.setIsProcessed(1);
                ban.setProcessedTime(now);
                ban.setUnbanReason(unbanReason);
                articleBanService.update(ban, new QueryWrapper<ArticleBan>().eq("article_id", articleId));
            });

            String contentTemplate = String.format("您的文章已解封，原因：%s", unbanReason);
            userIds.stream()
                    .distinct() // 去重用户ID
                    .forEach(userId -> messageUtil.sendSecurityMessage(userId, contentTemplate));

            return DataVo.ok("解封成功，已发送通知");

        } catch (Exception e) {
            return DataVo.error(e.getMessage() != null ? e.getMessage() : "解封失败");
        }
    }
}